<?php
/**
 * 验证码相关
 * User: wuhao
 * Date: 2017/5/5
 * Time: 10:05
 */
namespace app\backend\controller;

use app\backend\model\Member as Member;
use Business\Business;
use Business\sms\VComSms;
use think\Controller;

class VerifyCodeController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    //生成登录及其他的图形验证码
    public function getCode()
    {
        //判断来源地址
        $referer = I('server.HTTP_REFERER');
        $host    = I('server.HTTP_HOST');
        if(strrpos($referer, $host) === false) {
            exit('非法请求');
        }
        $num = genRandomString(4);
        $numLen = strlen($num);
        $imagewidth=60;             //定义画布的宽
        $imageheight=25;                //定义画布的高
        $numimage = imagecreate($imagewidth,$imageheight);          //创建画布
        imagecolorallocate($numimage,230,230,230);              //设置画布颜色
        for($i=0;$i<$numLen;$i++){                           //循环读取随机数
            $x = mt_rand(1,8)+$imagewidth*$i/$numLen;
            $y = mt_rand(1,$imageheight/4);
            $color=imagecolorallocate($numimage,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150)); //定义图像的颜色
            imagestring($numimage,5,$x,$y,$num[$i],$color);         //将随机数写入到画布中
        }
        for($i=0;$i<4;$i++){         //for循环语句生成干扰线
            $randcolor=imagecolorallocate($numimage,rand(100,255),rand(100,255),rand(100,255)); //定义颜色
            imageline($numimage,rand()%$imagewidth,rand()%$imageheight,rand()%$imagewidth,rand()%$imageheight,$randcolor); //生成干扰线
        }
        header("content-type:image/png");   //设置页面编码
        imagepng($numimage);            //生成图像
        imagedestroy($numimage);            //释放资源
        $_SESSION["auth_code"]=$num;
    }

    //生成注册图形验证码
    public function getRegCode()
    {
        //判断来源地址
        $referer = I('server.HTTP_REFERER');
        $host    = I('server.HTTP_HOST');
        if(strrpos($referer, $host) === false) {
            exit('非法请求');
        }
        $num = genRandomString(4);
        $numLen = strlen($num);
        $imagewidth=60;             //定义画布的宽
        $imageheight=25;                //定义画布的高
        $numimage = imagecreate($imagewidth,$imageheight);          //创建画布
        imagecolorallocate($numimage,230,230,230);              //设置画布颜色
        for($i=0;$i<$numLen;$i++){                           //循环读取随机数
            $x = mt_rand(1,8)+$imagewidth*$i/$numLen;
            $y = mt_rand(1,$imageheight/4);
            $color=imagecolorallocate($numimage,mt_rand(0,150),mt_rand(0,150),mt_rand(0,150)); //定义图像的颜色
            imagestring($numimage,5,$x,$y,$num[$i],$color);         //将随机数写入到画布中
        }
        for($i=0;$i<16;$i++){         //for循环语句生成干扰线
            $randcolor=imagecolorallocate($numimage,rand(100,255),rand(100,255),rand(100,255)); //定义颜色
            imageline($numimage,rand()%$imagewidth,rand()%$imageheight,rand()%$imagewidth,rand()%$imageheight,$randcolor); //生成干扰线
        }
        header("content-type:image/png");   //设置页面编码
        imagepng($numimage);            //生成图像
        imagedestroy($numimage);            //释放资源
        $_SESSION["auth_code"]=$num;
    }

    /**
     * 检测图形验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @param  string  $code      图形验证码
     * @return
     */
    public function checkCode()
    {
        $code     = I('post.code', '', 'strval');
        if (!$code) {
            $this->apiReturn(406, [], '不能为空');
        }

        if (isset($_SESSION['auth_code'])) {
            if (strtolower($code) != strtolower($_SESSION['auth_code'])) {
                $this->apiReturn(402, [], '图形验证码错误');
            } else {
                $this->apiReturn(200, [], '');
            }
        } else {
            $this->apiReturn(403, [], '图形验证码未生成');
        }
    }

    /**
     * 检测手机验证码
     * @date   2017-05-04
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     * @param  string  $code           手机验证码
     * @param  string  $key            reg 注册验证码;
     *                                  change_mobile 更换手机号验证码;
     *                                  reset_pwd 重置密码验证;
     *                                  alipay 更新支付宝账号;
     *                                  withdraw_pwd 更新提现密码;
     *                                  bank_card    绑定银行卡
     *                                  bank_card_del 删除银行卡
     *
     * @return
     */
    private function checkMobileCode($mobile, $code, $key)
    {
        //检查验证码
        $sms = new VComSms();
        $check = $sms->ChkVerifyCode($mobile, $key, $code);
        if (!$check) {
            $this->apiReturn(403, [], '手机验证码错误');
        } elseif ($check === -1) {
            $this->apiReturn(403, [], '验证码已经失效');
        } else {
            $this->apiReturn(200, [], '验证通过');
        }
    }

    /**
     * 发送验证码
     * @date   2017-05-04
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     * @param  string  $key            reg 注册验证码;
     *                                  change_mobile 更换手机号验证码;
     *                                  reset_pwd 重置密码验证;
     *                                  alipay 更新支付宝账号;
     *                                  withdraw_pwd 更新提现密码;
     *                                  bank_card    绑定银行卡
     *                                  bank_card_del 删除银行卡
     *
     * @return
     */
    private function sendMobileCode($mobile, $key)
    {
        $business = new Business();
        $res = $business->sendCode($mobile, $key);

        if ($res['code'] == 200) {
            $this->apiReturn($res['code'], [], '发送成功');
        } elseif ($res['code'] == 141) {
            $this->apiReturn($res['code'], [], '发送间隔低于2分钟');
        } else {
            $this->apiReturn($res['code'], [], '发送失败');
        }
    }

    /**
     * 注册 - 发送验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @param  int  $mobile  手机号
     *
     * @return
     */
    public function SendVcode()
    {
        $mobile = I('post.mobile', '', 'strval');

        if (!ismobile($mobile)) {
            $this->apiReturn(405, [], '手机号格式错误');
        }
        $memberModel = new Member();
        if ($memberModel->getMemberInfo(['mobile' => $mobile], 'id')) {
            $this->apiReturn(404, [], '手机号已注册过了');
        }
        $this->sendMobileCode($mobile, 'reg');
    }

    /**
     * @comment 登录 - 发送验证码
     * @author wuhao
     */
    public function sendLoginCode()
    {
        $mobile = I('post.mobile', '', 'strval');

        if (!ismobile($mobile)) {
            $this->apiReturn(405, [], '手机号格式错误');
        }
        $memberModel = new Member();
        if (!$memberModel->getMemberInfo(['mobile' => $mobile], 'id')) {
            $this->apiReturn(404, [], '手机号尚未注册');
        }
        $this->sendMobileCode($mobile, 'login');
    }

    /**
     * 忘记密码 - 发送短信验证码
     * @date   2017-05-04
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     *
     * @return
     */
    public function sendResetCode()
    {
        $mobile = I('post.mobile', '', 'strval');
        if (!ismobile($mobile)) {
            $this->apiReturn(405, [], '手机号格式错误');
        }
        $memberModel = new Member();
        if (!$memberModel->getMemberInfo(['mobile' => $mobile], 'id')) {
            $this->apiReturn(404, [], '手机号未注册');
        }
        $this->sendMobileCode($mobile, 'reset_pwd');
    }

    /**
     * 忘记密码 - 验证码验证
     * @date   2017-05-03
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     * @param  string  $mobile_code    手机验证码
     *
     * @return
     */
    public function checkReset()
    {
        $mobile = I('post.mobile', '', 'strval');
        $mobileCode = I('post.mobile_code', '', 'strval');
        if (!ismobile($mobile)) {
            $this->apiReturn(405, [], '手机号格式错误');
        }
        $memberModel = new Member();
        if (!$memberModel->getMemberInfo(['mobile' => $mobile], 'id')) {
            $this->apiReturn(404, [], '手机号未注册');
        }
        $this->checkMobileCode($mobile, $mobileCode, 'reset_pwd');
    }

    /**
     * 更换手机号 - 发送短信验证码
     * @date   2017-05-04
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     * @param  int     $type           0=旧手机号发短信 1=新手机号发送
     *
     * @return
     */
    public function sendChangeMobileCode()
    {
        $memberId = $this->isLogin();
        $mobile = I('post.mobile', '', 'strval');
        $type   = I('post.type', 0, 'intval');
        if (!ismobile($mobile) || !in_array($type, [1, 0])) {
            $this->apiReturn(405, [], '参数格式错误');
        }
        $memberModel = new Member();
        $memberInfo  = $memberModel->getMemberInfoById($memberId, 'id, mobile');
        if (!$memberInfo) {
            $this->apiReturn(404, [], '用户信息有误');
        }
        if ($type == 0) {//检验当前手机号是否是登录人的
            if ($mobile != $memberInfo['mobile']) {
                $this->apiReturn(404, [], '非登录人');
            }
        } else {//检验新手机号是否已注册过
            if ($memberModel->getMemberInfo(['mobile' => $mobile], 'id')) {
                $this->apiReturn(404, [], '手机号已经注册过了');
            }
        }
        $this->sendMobileCode($mobile, 'change_mobile');
    }

    /**
     * 更换手机号 检验验证码
     * @date   2017-05-04
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     * @param  string  $mobile_code    手机验证码
     * @param  int     $type           0=旧手机号验证 1=新手机号验证
     *
     * @return
     */
    public function checkChangeMobile()
    {
        $memberId = $this->isLogin();
        $mobile     = I('post.mobile', '', 'strval');
        $mobileCode = I('post.mobile_code', '', 'strval');
        $type       = I('post.type', 0, 'intval');
        if (!ismobile($mobile) || !$mobileCode || !in_array($type, [1,0])) {
            $this->apiReturn(405, [], '参数格式错误');
        }
        $memberModel = new Member();
        $memberInfo  = $memberModel->getMemberInfoById($memberId, 'id, mobile');
        if (!$memberInfo) {
            $this->apiReturn(404, [], '用户信息有误');
        }
        if ($type == 0) {//检验当前手机号是否是登录人的
            if ($mobile != $memberInfo['mobile']) {
                $this->apiReturn(404, [], '非登录人');
            }
        } else {//检验新手机号是否已注册过
            if ($memberModel->getMemberInfo(['mobile' => $mobile], 'id')) {
                $this->apiReturn(404, [], '手机号已经注册过了');
            }
        }
        $this->checkMobileCode($mobile, $mobileCode, 'change_mobile');
    }

    /**
     * 更新支付宝账号 - 发送短信验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @return
     */
    public function sendAlipayCode()
    {
        $memberInfo = $this->getLoginInfo();
        $this->sendMobileCode($memberInfo['mobile'], 'alipay');
    }

    /**
     * 更新支付宝账号 检验验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     * @param  string  $mobile_code    手机验证码
     *
     * @return
     */
    public function checkAlipayCode()
    {
        $memberInfo = $this->getLoginInfo();
        $mobileCode = I('post.mobile_code', '', 'strval');
        if (!$mobileCode) {
            $this->apiReturn(405, [], '参数格式错误');
        }
        $this->checkMobileCode($memberInfo['mobile'], $mobileCode, 'alipay');
    }

    /**
     * 更新支付密码 - 发送短信验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @param  int     $mobile         手机号
     *
     * @return
     */
    public function sendWithdrawPwdCode()
    {
        $memberInfo = $this->getLoginInfo();
        $this->sendMobileCode($memberInfo['mobile'], 'withdraw_pwd');
    }

    /**
     * 更新支付密码 检验验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @param  string  $mobile_code    手机验证码
     *
     * @return
     */
    public function checkWithdrawPwdCode()
    {
        $memberInfo = $this->getLoginInfo();
        $mobileCode = I('post.mobile_code', '', 'strval');
        if (!$mobileCode) {
            $this->apiReturn(405, [], '参数格式错误');
        }
        $this->checkMobileCode($memberInfo['mobile'], $mobileCode, 'withdraw_pwd');
    }

    /**
     * 绑定银行卡 - 发送短信验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @return
     */
    public function sendBankCardCode()
    {
        $memberInfo = $this->getLoginInfo();
        $this->sendMobileCode($memberInfo['mobile'], 'bank_card');
    }


    /**
     * 删除银行卡 - 发送短信验证码
     * @date   2017-05-05
     * @author wuhao
     *
     * @return
     */
    public function sendDelBankCardCode()
    {
        $memberInfo = $this->getLoginInfo();
        $this->sendMobileCode($memberInfo['mobile'], 'bank_card_del');
    }
}